<?php

namespace app\enterprise\controller;

use app\enterprise\model\course\Teacher as TeacherModel;
use app\enterprise\model\course\TeacherCert as TeacherCertModel;
use app\enterprise\model\course\Courseware;
use app\enterprise\service\DataType;
use app\Request;
use think\exception\ValidateException;

class Teacher extends Enterprise
{
    public function list()
    {
        $limit = input('size', 10);
        $page = input('page', 1);
        $username = input('username', '');
        $idcard = input('idcard', '');
        $cert_code = input('cert_code', '');

        $where = [];

        $where[] = ['company_id', '=', $this->adminId];

        if ($username) {
            $where[] = ['username', 'like', '%' . $username . '%'];
        }
        if ($idcard) {
            $where[] = ['idcard', 'like', '%' . $idcard . '%'];
        }

        if ($cert_code) {
            $ids = TeacherCertModel::where('cert_code', 'like', '%' . $cert_code . '%')
                ->column('teacher_id');
            $where[] = ['id', 'in', $ids];
        }

        $data = TeacherModel::where('status', 1)
            ->order('id desc')
            ->where($where)
            ->with('user')
            ->paginate($limit);

        foreach ($data as $key => &$value) {
            if (!empty($value['user'])) {
                $value['company_name'] = $value['user']['company_name'];
                unset($value['user']);
            } else {
                $value['company_name'] = '未知';
            }

            if (!empty($value['idcard'])) {
                $value['idcard'] = idCardMask($value['idcard']);
            }
        }
        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total()
        ]);
    }

    public function listAll()
    {
        $param = $this->request->param();
        try {
            validate([
                'create_type|教师所属资源' => 'require|in:1,2'
            ])->check($param);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        $create_type = $param['create_type'];

        $company_id = $create_type == 2 ? $this->adminId : 0;
        $where = [];
        $where[] = ['company_id', '=', $company_id];
        //        if (!empty(input('username'))) {
        //            $where[] = ['username', 'like', '%' . $param['username'] . '%'];
        //        }
        //        if (!input('mobile')) {
        //            $where[] = ['mobile', 'like', '%' . $param['mobile'] . '%'];
        //        }

        $teachers = TeacherModel::where('status', '=', 1)->where($where)->order('sort desc, id asc')->select()->toArray();

        return app('json')->success([
            'list' => $teachers,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'username',
            'idcard',
            'mobile',
            'idcard_img',
            'idcard_img2',
            'graduation_img',
            'degree_img',
            'company_id'
        ]);

        $certs = input('certs', []);
        $id = input('id', '');
        try {
            validate([
                'username|姓名' => 'require|max:15',
                'idcard|身份证号' => [
                    //                    'require',
                    'regex:/^(\d{15}$|^\d{17}[\dXx])$/'
                ],
                'mobile|手机号' => [
                    'require',
                    'regex:/^1[3456789]\d{9}$/'
                ],
                //                'idcard_img|身份证正面' => 'require',
                'idcard_img2|身份证反面' => 'max:255',
                //                'graduation_img|毕业证书' => 'require',
                'degree_img|学位证' => 'max:255'
            ])->check($data);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        $lockKey = 'teacher_save_idcard_lock_' . $this->adminId . '_' . md5($data['idcard']);
        if (!cache($lockKey, '1', 60, 'teacher')) { // 尝试加锁
            return app('json')->fail('请勿频繁提交');
        }

        try {
            foreach ($certs as $key => $cert) {
                try {
                    validate([
                        'type_id|资质类型' => 'require',
                        'cert_code|职业证书编号' => 'require',
                        'expire_type|是否永久有效' => 'require|in:1,2',
                        'start_time|证书有效期开始时间' => 'requireIf:expire_type,2',
                        'end_time|证书有效期结束时间' => 'requireIf:expire_type,2',
                        'cert_imgs|证书照片' => 'require',
                    ])->check($cert);
                    if ($cert['expire_type'] == 1) {
                        $cert['expire_type'] = 1;
                        $certs[$key]['start_time'] = 0;
                        $certs[$key]['end_time'] = 0;
                    } else {
                        $certs[$key]['start_time'] = strtotime($cert['start_time']);
                        $certs[$key]['end_time'] = strtotime($cert['end_time']);
                    }
                } catch (ValidateException $e) {
                    return app('json')->fail($e->getError());
                }
            }
            $data['company_id'] = $this->adminId;
            if ($id) {

                $teacher = TeacherModel::getOne($id);

                if (empty($teacher)) {
                    return app('json')->fail('数据不存在');
                }

                if ($teacher['company_id'] != $this->adminId) {
                    return app('json')->fail('没有操作权限');
                }

                if ($teacher->idcard != $data['idcard']) {
                    if (TeacherModel::where('idcard', '=', $data['idcard'])->where('company_id', '=', $this->adminId)->where('status', '=', 1)->value('id')) {
                        return app('json')->fail('身份证号已存在');
                    }
                }

                $res = TeacherModel::where('id', $id)
                    ->update($data);
                TeacherCertModel::arrayDelete(['teacher_id' => $id]);
            } else {

                // 判断手机号是否存在
                if (TeacherModel::where('idcard', '=', $data['idcard'])->where('company_id', '=', $this->adminId)->where('status', '=', 1)->value('id')) {
                    return app('json')->fail('身份证号已存在');
                }
                // 创建人
                $data['creator_id'] = $this->adminId;
                $teacher = TeacherModel::create($data);
                $id = $teacher->getKey();
            }
            if ($certs && is_array($certs) && count($certs) > 0) {
                foreach ($certs as $key => $cert) {
                    $certs[$key]['teacher_id'] = $id;
                }
                $teacherCertModel = new TeacherCertModel();
                $teacherCertModel->saveAll($certs);
            }
            return app('json')->success();
        } finally {
            cache($lockKey, null);
        }
    }

    public function delete()
    {
        $id = input('id', '');

        if (!$id) {
            return app('json')->fail('参数错误');
        }

        $teacher = TeacherModel::getOne($id);

        if (empty($teacher)) {
            return app('json')->fail('数据不存在');
        }

        if ($teacher['company_id'] != $this->adminId) {
            return app('json')->fail('没有操作权限');
        }

        if (Courseware::where('teacher_id', $id)->find()) {
            return app('json')->fail('有课件关联了该教师，无法删除');
        }

        TeacherModel::dataDelete($id);

        TeacherCertModel::arrayDelete(['teacher_id' => $id]);

        return app('json')->success();
    }


    public function info()
    {
        $id = input('id', '');

        if (!$id) {
            return app('json')->fail('参数错误');
        }

        $teacher = TeacherModel::getOne($id);

        if (empty($teacher)) {
            return app('json')->fail('数据不存在');
        }

        $teacherCerts = TeacherCertModel::where('teacher_id', $id)->select()->toArray();


        if (!empty($teacherCerts)) {

            $cert_types = array_column(DataType::getCertType(), 'name', 'id');

            foreach ($teacherCerts as $key => $cert) {
                $teacherCerts[$key]['type_name'] = $cert_types[$cert['type_id']] ?? '';
                // 格式化开始时间和结束时间, 格式 YYYY-MM-dd
                if ($cert['expire_type'] == 1) {
                    $teacherCerts[$key]['start_time'] = '';
                    $teacherCerts[$key]['end_time'] = '';
                } else {
                    $teacherCerts[$key]['start_time'] = date('Y-m-d', $cert['start_time']);
                    $teacherCerts[$key]['end_time'] = date('Y-m-d', $cert['end_time']);
                }
            }
        }
        $teacher['certs'] = $teacherCerts;

        return app('json')->success([
            'info' => $teacher
        ]);
    }

    public function certTypes()
    {
        $certTypes = \app\enterprise\service\DataType::getCertType();

        return app('json')->success([
            'list' => $certTypes
        ]);
    }
}
